package com.leha.mp.core.services.imp;

import com.github.pagehelper.PageHelper;
import com.leha.mp.core.constants.CoreErrorDict;
import com.leha.mp.core.dao.MpDoctorCodeMapper;
import com.leha.mp.core.entity.mybatis.MpDoctorCode;
import com.leha.mp.core.entity.mybatis.MpDoctorCodeExample;
import com.leha.mp.core.services.ErrorMessageServices;
import com.leha.mp.core.services.WxMPQrCodeServices;
import com.leha.mp.core.services.WxMPServices;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WxMPQrCodeServicesImpl implements WxMPQrCodeServices {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    MpDoctorCodeMapper doctorCodeMapper;
    @Autowired
    WxMPServices wxMPServices;
    @Autowired
    ErrorMessageServices errorMessageServices;

    @Override
    public MpDoctorCode generateDoctorCode(Integer DoctorId) {
        MpDoctorCode code = doctorCodeMapper.selectByPrimaryKey(DoctorId);
        if(code != null) {
            return code;
        }
        try{
            code = new MpDoctorCode();
            WxMpQrCodeTicket QRCode = wxMPServices.generateQRCode(DoctorId);
            code.setDoctorId(DoctorId);
            code.setQrcode(QRCode.getUrl());
            code.setTicket(QRCode.getTicket());
            code.setInsertTime(new Date());
            doctorCodeMapper.insert(code);
        } catch (Exception e) {
            errorMessageServices.setError(CoreErrorDict.WXQRCodeRequsetFaild);
            logger.error("generate QRCodeError!{}", e);
            return null;
        }
        return code;
    }

    @Override
    public List<MpDoctorCode> ListDoctorCode(Integer pageNum, Integer pageSize) {
        if(pageNum == null || pageNum==0) {
            pageNum = 1;
        }
        if(pageSize == null || pageSize==0) {
            pageSize = 12;
        }
        PageHelper.startPage(pageNum, pageSize);
        return doctorCodeMapper.selectByExample(new MpDoctorCodeExample());
    }
}
